/*
 * @Author: firefly717
 * @Date: 2024-06-23 16:10:02
 * @LastEditTime: 2024-06-23 16:22:55
 * @Description: 
 */



main() {
  _stream();
  // _stream2();
  // _stream3();
  // _stream4();
  // _stream5();
}

///用于创建一个每隔一秒发送一次无限事件的流,并打印出值
void _stream() async {
  Duration interval = Duration(seconds: 1);
  Stream stream = Stream.periodic(interval, (data) => data);
  await for (int i in stream) {
    print(i);
  }
}

void _stream2() async {
  Duration interval = Duration(seconds: 1);
  Stream stream = Stream.periodic(interval, (data) => data);
  stream = stream.take(10); //指定发送事件个数
  await for (int i in stream) {
    print(i);
  }
}

void _stream3() async {
  Duration interval = Duration(seconds: 1);
  Stream stream = Stream.periodic(interval, (data) => data);
// stream = stream.take(10);
  stream = stream.takeWhile((data) {
    return data < 10;
  });
  await for (int i in stream) {
    print(i);
  }
}

void _stream4() async {
  Duration interval = Duration(seconds: 1);
  Stream stream = Stream.periodic(interval, (data) => data);
  stream = stream.take(10);
  stream = stream.skip(2);
  await for (int i in stream) {
    print(i);
  }
}

void _stream5() async {
  Duration interval = Duration(seconds: 1);
  Stream stream = Stream.periodic(interval, (data) => data);
  stream = stream.take(10);
  stream.listen((data) {
    print(data);
  }, onError: (error) {
    print('流发生错误');
  }, onDone: () {
    print('流已完成');
  }, cancelOnError: false);
}